<template>
  <div class="container">
    <el-form ref="form"  label-width="80px" :model="form" :rules="rules" >
      <el-form-item label="学科名称" prop="subjectName">
        <el-input v-model="form.subjectName" placeholder="请输入学科名称" style="width:280px"></el-input>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-switch
          v-model="form.isFrontDisplay"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </el-form-item>
      <el-form-item >
        <el-button @click="cancelFn">取消</el-button>
        <el-button type="primary" @click="submitFn">确认</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { add as addAPI, detail as detailAPI, update as updateAPI } from '@/api/hmmm/subjects'
export default {
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    row: {
      type: Object
      // required: true
    }

  },
  data () {
    return {
      rules: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: ['blur'] }
        ]
      },
      form: {
        isFrontDisplay: true,
        subjectName: ''
      }
    }
  },
  mounted () {
    // 编辑状态
    if (this.isEdit) {
      this.editFn()
    }
  },
  methods: {
    // 点击提交
    submitFn () {
      // 兜底验证
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.addFn()
      }
      )
    },
    // 点击取消
    cancelFn () {
      // 1.通知父组件关闭弹层
      this.$emit('closeDialog')

      // 2.清空表单
      this.form = {
        isFrontDisplay: true,
        subjectName: ''
      }
      // 3.清空校验

      this.$refs.form.resetFields()
    },
    // 添加学科
    async addFn () {
      try {
        // 1.调取接口，获取数据
        const res = await addAPI(this.form)
        console.log('添加成功', res)

        // // 2.通知父组件关闭弹层
        // this.$emit('closeDialog')
        this.cancelFn()

        // 3.更新列表
        this.$emit('update')
        this.$message.success('添加成功')
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 修改
    async editFn () {
      try {
        // 1.获取学科详情
        const res = await detailAPI(this.row)
        console.log('学科详情', res)

        // 2. 回填表单
        this.form = res.data
        console.log(res.data)

        // 对返回的数据进行处理 true--1 false--0
        this.form.isFrontDisplay = res.data.isFrontDisplay === 1
        // console.log(this.form.isFrontDisplay)
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    // 做修改
    async doEdit () {
      try {
        // 1. 调取接口
        const res = await updateAPI(this.form)
        console.log('修改学科', res)

        // 2.清空
        this.cancelFn()

        // 3.更新列表
        this.$emit('update')
        this.$message.success('修改成功')
      } catch (err) {
        this.$message.error(err.message)
      }
    }

  }
}

</script>

<style scoped lang='scss'></style>
